/*
 * Author: 李波（Edwin Lee)
 * Date: 2024-06-14 19:02:35
 * FilePath: /chat/src/server/chatserver.cc
 * LastEditTime: 2024-06-18 19:11:23
 * version: 1.0
 * Description: 服务器方法
 */

#include "chatserver.h"
#include "chatservice.h"
#include "json.hpp"

#include <functional>
#include <string>

using namespace std;
using namespace placeholders;
using json = nlohmann::json;

ChatServer::ChatServer(EventLoop* loop, const InetAddress& listenAddr, const string& nameArg)
    :server_(loop, listenAddr, nameArg)
    ,loop_(loop)
{
    //注册连接回调
    server_.setConnectionCallback(std::bind(&ChatServer::onConnection, this, _1));
    //
    server_.setMessageCallback(std::bind(&ChatServer::onMessage, this, _1, _2, _3));

    //设置线程数量
    server_.setThreadNum(4);
}

void ChatServer::start()
{
    server_.start();
}

void ChatServer::onConnection(const TcpConnectionPtr& conn)
{
    //客户断开连接
    if(!conn->connected())
    {
        ChatService::getInstance()->clientCloseException(conn);
        //printf("connect shutdown!\n");
        conn->shutdown();
    }
}


void ChatServer::onMessage(const TcpConnectionPtr& conn, Buffer* buffer, Timestamp time)
{
    string buf = buffer->retrieveAllAsString();
    //数据的反序列化
    json js = json::parse(buf);

    // 回调消息绑定好的事件处理器，来执行相应的任务
    auto msgHandler = ChatService::getInstance()->getHandler(js["msgid"].get<int>());
    msgHandler(conn, js, time);
}

